// pages/detail/detail.js
import request from '../../utils/config.js';
import util from '../../utils/util.js';
const app = getApp();
Page({
    data: {
        currentNum: 0,
        periodDaysColor: '#58b5e1',
        showAble: true,
        caseDetail: {},
        enforceCurrInfos: {},
        enforceStep: {},
        roles: [],//用户权限
        otherInput: [],
        branchList: [],
        nextStepIndex: 'none',
        configType: true,
        isFavor: "Y",
        imgSign: '',
        array: ['法律文书生效测试结束', '美国', '中国', '巴西', '日本'],
        isloading: false,
        enforceStepList: [],
        breakReasons: [],
        breakReasonsIndex: 'none',
        breakReasonsDesc: '',
        breakTypes: [{
          id: '1',
          breakType: "自动恢复"
        }, {
          id: '2',
          breakType: "长期生效"
        }],
        breakTypeIndex: 0,
        ROLE_BreakForEver: false,
        modalForInput: false,
        modalClose:false,
        enforceStepRecordWithBLOBs: [],
        table_faguan:[],
        table_caibao:[],
        table_huikuan: [],
        modalForHuiKuan:false,
        awardEndDate:"",
        huiKuanFlag:"",
        huiKuanFlagId:'',
        userCanseeType:true,
        showEdit: false,
        edit_value: "",
        editId: "",
        newDateTime: new Date().getTime(),
        tab3Flag: false,
        userVisualResult :true,
        stepDesc: '',
        subZindex:10,
        items: [
            { value: '选择',slt:'Y', checked: 'true' },
            { value: '手工输入', slt: 'N',}
        ],
        animationM: {},
        animationS: {},
        showBranch: false,
        branchItems: [],
        branchNextSteptId: "",
        onChangeData: {},
        caseId:"",
        showModel: false,
        showHomeBtn: false,
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      console.log("诉讼===", options)
      if (options.caseId) {
        this.setData({
          caseId: options.caseId,
          showHomeBtn: true
        });
      }
    },  

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
      if (!wx.getStorageSync('token')) {
        //未登录
        wx.showModal({
          title: '未登录',
          content: '请先登录系统',
          confirmText: '前去登录',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../index/index',
              })
            } else if (res.cancel) {
            }
          }
        })
        return
      }
      //判断案件进入的场景（列表进入、推送消息进入）
      if (app.globalData.userInfo && !this.data.caseId) {//列表进入
        this.setData({
          caseDetail: app.globalData.caseDetailData,
          roles_quanxian: app.globalData.loginUserInfo.roles.includes('ROLE_LawsuitStepRecordManage'),
          ROLE_BreakForEver: app.globalData.loginUserInfo.roles.includes('ROLE_BreakForEver')
        });
        this.initMethod();
      } else {//消息推送
        app.globalData.caseDetailData ={};
        let _that = this;
        if (!app.globalData.userInfo) {//判断是否登录过
          app.getAuthUserInfo((res) => {
            res.userInfo.nickName = res.userInfo.nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
            app.globalData.userInfo = res.userInfo;
            app.globalData.encryptedData = res.encryptedData;
            app.globalData.iv = res.iv;
            _that.getOpenid(_that);
          }, (res) => {
            _that.setData({
              showModel: true
            })
          });
        } else {//已登录
          //先还原赋值
          app.globalData.caseDetailData.caseId = this.data.caseId;
          this.setData({
            caseDetail: app.globalData.caseDetailData,
            roles_quanxian: app.globalData.loginUserInfo.roles.includes('ROLE_LawsuitStepRecordManage'),
            ROLE_BreakForEver: app.globalData.loginUserInfo.roles.includes('ROLE_BreakForEver')
          });
          this.initMethod();
        }
      }
    },

    //初始化
    initMethod: function () {
      this.get_enforceCurrInfos()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
      this.toast = this.selectComponent("#toast");
      this.homeBtn = this.selectComponent("#homeBtn");
    },

    //组件授权回调
    _setAuthorization: function (e) {
      let that = this;
      that.getOpenid(that);
    },

    //点击返回首页组件回调
    _goHomeBtn: function (e) {
      wx.setStorageSync("flagName", "lawsuit");
      wx.redirectTo({
        url: '../syIndex/syIndex?flagName=lawsuit'
      })
    },

    //获取openid
    getOpenid: (_that) => {
      app.getGlobalOpenid(function (token) {
        if (token) {
          //开始校验看token值
          _that.checkToken();
        } else {
          wx.hideLoading();
          //未登录
          wx.showModal({
            title: '未登录',
            content: '请先登录系统',
            confirmText: '前去登录',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '../index/index',
                })
              } else if (res.cancel) {
              }
            }
          })
        }
      });
    },

    //检验token值
    checkToken: function () {
      let _that = this;
      app.checkGlobalToken(function (res) {
        _that.setData({
          loginUserInfo: res.loginUserInfo,
        });
        let tempList = res.tempList;
        let flagName = res.flagName;
        let jurisdiction = res.jurisdiction;
        let roleQuanxian = res.roleQuanxian;
        let department = res.department;
        if (tempList.length == 0) {
          wx.showModal({
            title: '对不起',
            content: '您的权限不足',
            confirmText: "知道了",
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '../index/index',
                })
              } else if (res.cancel) {
              }
            }
          })
          return;
        }

        //校验上次记住的部门权限是否还存在
        if (jurisdiction.indexOf(roleQuanxian) < 0) {
          wx.showModal({
            title: '对不起',
            content: "您的" + department + "权限不足",
            confirmText: "知道了",
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '../index/index',
                })
              } else if (res.cancel) {
              }
            }
          })
          return;
        }
        app.globalData.caseDetailData.caseId = _that.data.caseId;
          _that.setData({
          caseDetail: app.globalData.caseDetailData,
          roles_quanxian: app.globalData.loginUserInfo.roles.includes('ROLE_LawsuitStepRecordManage'),
          ROLE_BreakForEver: app.globalData.loginUserInfo.roles.includes('ROLE_BreakForEver')
        });
        _that.initMethod();
      }, function (res) {
        //登录超时
        wx.showModal({
          title: '登录超时',
          content: '点击确定重新登录',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../index/index',
              })
            } else if (res.cancel) {
            }
          }
        })
      });
    },


    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },


    // 步骤描述
    change_trackDesc: function (e) {
        console.log(e)
        this.setData({
            stepDesc: e.detail
        })
    },
    // 手动输入 单选框
    radioHandChange: function (e) {
        console.log('radio发生change事件，携带value值为：', e.detail.value)
        if (e.detail.value == '选择') {
            this.setData({
              configType: true
            })
        } else if (e.detail.value == '手工输入'){
            this.setData({
              configType: false
            })
        }
    },
    // 获取caseLi高度
    getRect: function () {
      let _this = this;
      wx.createSelectorQuery().select('#caseLiId').boundingClientRect(function (rect) {
        rect.id      // 节点的ID
        rect.height  // 节点的高度
        _this.showCaseLi(rect.height)
      }).exec()
    },
    showCaseLi: function (height) {
      console.log(height)
      var animation = wx.createAnimation({
        duration: 200,
        timingFunction: "ease",
        delay: 0
      })
      this.animation = animation
      animation.height(height).step()

      var animation2 = wx.createAnimation({
        duration: 200,
        timingFunction: "ease",
        delay: 0
      })
      this.animation2 = animation2
      animation2.height(0).step()

      this.setData({
        animationM: animation.export(),
        animationS: animation2.export(),
      })
    },
    toTop: function() {
      this.animation.height(0).step()
      this.animation2.height(34).step()
      this.setData({
        animationM: this.animation.export(),
        animationS: this.animation2.export()
      })
    },

    get_enforceCurrInfos() {
        let _this = this;
        wx.showLoading({ title: ' ', mask: true})
        request.requestMisApi('get', "lawsuitCurrInfos/" + app.globalData.caseDetailData.caseId, {}, (res) => {
            if (res.code == '00') {
                let enforceCurrInfos = JSON.parse(res.body)
                _this.setData({
                  stepDesc: enforceCurrInfos.stepDesc
                })
                console.log("enforceCurrInfos=", enforceCurrInfos)
                let imgSign = '';
                let periodDaysColor = '';
                if (enforceCurrInfos.periodDays * 1 > enforceCurrInfos.totalDays * 1) {
                    periodDaysColor = '#ff6161';
                } else {
                    periodDaysColor = '#58b5e1'
                }
                if (enforceCurrInfos.status === '2') {
                    imgSign = "state2.png";
                    periodDaysColor = "#a1a1a1";
                } else if (enforceCurrInfos.status === '3') {
                    imgSign = "state5.png";
                    periodDaysColor = '#1aac19'
                } else if (enforceCurrInfos.status === '4') {
                    imgSign = "state4.png";
                    periodDaysColor = '#1aac19'
                } else if (enforceCurrInfos.status === '1') {
                    imgSign = enforceCurrInfos.expireSign == '1' ? 'state3.png' : 'state1.png';
                    periodDaysColor = enforceCurrInfos.expireSign == '1' ? '#ff6161' : '#58b5e1';
                }
                //为了解决从消息场景进入小程序要对全局赋值
                app.globalData.caseDetailData.debtorName = enforceCurrInfos.debtorName;//被告
                app.globalData.caseDetailData.creditorName = enforceCurrInfos.creditorName;//被告

                _this.setData({
                    enforceCurrInfos: enforceCurrInfos,
                    periodDaysColor: periodDaysColor,
                    isFavor: enforceCurrInfos.isFavor,
                    imgSign: imgSign,
                    caseDetail: app.globalData.caseDetailData
                });
                if (_this.data.currentNum == '1') {
                    _this.tab2();
                }
                if (enforceCurrInfos.stepId) {
                    request.requestMisApi('get', "lawsuitStepConfigs/" + enforceCurrInfos.stepId, {}, (res) => {
                        let enforceStep = JSON.parse(res.body)
                        wx.hideLoading()
                        if (res.code == '00') {
                            let enforceStep = JSON.parse(res.body), otherInput = [], branchList = [];
                            console.log("enforceStep=", enforceStep)
                            if (enforceStep.isBranch === 'N' && enforceStep.inputJson != '[]') {
                                JSON.parse(enforceStep.inputJson).forEach(function (item) {
                                    if (item.type === 'date') {
                                        // item.value = util.timetrans(new Date(), 'day');
                                        item.value = '';
                                    } else if (item.type === 'dateTime') {
                                        // item.value_date = util.timetrans(new Date(), 'day');
                                        // item.value_time = util.timetrans(new Date(), 'timeHM');
                                        item.value_date = '';
                                        item.value_time = '';
                                    }
                                    otherInput.push(item)
                                })
                            }
                            if (enforceStep.isBranch === 'Y' && enforceStep.branchJson != '[]') {
                                JSON.parse(enforceStep.branchJson).forEach(function (item) {
                                    item.branchDesc = item.branchName + " -> " + item.nextStep.split('-')[1]
                                    branchList.push(item)
                                })
                            }
                            _this.setData({
                                enforceStep: enforceStep, otherInput: otherInput, branchList: branchList
                            });
                            _this.get_enforceStep()
                        }
                    }, (res) => {
                        console.log("接口错误=", res)
                    });
                } else {
                    wx.hideLoading()
                    _this.setData({
                        enforceStep: {
                            isBranch: 'N',
                            inputJson: '[]',
                            branchJson: '[]',
                        }, otherInput: [], branchList: []
                    });
                    _this.get_enforceStep()
                }
            }
        }, (res) => {
            console.log("接口错误=", res)
        });
    },
    get_enforceStep() {
        let _this = this;
        if (this.data.enforceStepList.length != 0) {
            let nextStepIndex = 'none';
            this.data.enforceStepList.forEach(function (e, index) {
                if (e.stepId == _this.data.enforceStep.nextStepId && _this.data.enforceStep.isBranch === 'N') {
                    nextStepIndex = index;
                }
            })
            this.setData({
                // nextStepIndex: nextStepIndex
            });
            this.get_breakReasons()
            return;
        }
        request.requestMisApi('get', "lawsuitStepConfigs/alls", {}, (res) => {
            if (res.code == '00') {
                let nextStepIndex = 'none';
                JSON.parse(res.body).forEach(function (e, index) {
                    if (e.stepId == _this.data.enforceStep.nextStepId && _this.data.enforceStep.isBranch === 'N') {
                        nextStepIndex = index;
                    }
                })
                _this.setData({
                    enforceStepList: JSON.parse(res.body),
                    // nextStepIndex: nextStepIndex
                });
                console.log(JSON.parse(res.body))
            }
            _this.get_breakReasons()
        }, (res) => {
            console.log("接口错误=", res)
        });
    },
    get_breakReasons: function () {
        if (this.data.breakReasons.length > 0) {
            // return;
        }
        let _this = this;
        request.requestMisApi('get', "lawsuitBreakReasons",  {status: '0'}, (res) => {
            console.log("中断原因=", res)
            _this.setData({
                breakReasons: res,
            });
            if (_this.data.tab3Flag) {
                _this.tab3()
            }
        }, (res) => {
            console.log("接口错误=", res)
        });
    },
    // 收藏取消
    collect: function () {
        if (this.data.isloading) {
            return
        }
        this.setData({
            isloading: true
        });
        let _this = this;
        if (this.data.isFavor == "Y") {
            request.requestMisApi('get', "flyWorkPlace/unfavorCases/" + app.globalData.caseDetailData.caseId, {}, (res) => {
                console.log(res)
                if (res.code == '00') {
                    _this.setData({
                        isFavor: "N",
                        isloading: false
                    });
                }
            }, (res) => {
                console.log("接口错误=", res)
            });
        } else {
            request.requestMisApi('get', "flyWorkPlace/favorCases/" + app.globalData.caseDetailData.caseId, {}, (res) => {
                console.log(res)
                if (res.code == '00') {
                    _this.setData({
                        isFavor: "Y",
                        isloading: false
                    });
                }
            }, (res) => {
                console.log("接口错误=", res)
            });
        }
    },
    // 展开合并 文件列表
    toggle: function (e) {
        let index = e.currentTarget.dataset.index;
        let fileLength = e.currentTarget.dataset.filelength
        let enforceStepList = this.data.enforceStepRecordWithBLOBs;
        if (fileLength > 0) {
            if (enforceStepList[index].openFile) {
                enforceStepList.forEach(function (e) {
                    e.openFile = false;
                });
            } else {
                enforceStepList.forEach(function (e) {
                    e.openFile = false;
                });
                enforceStepList[index].openFile = true;
            }
            this.setData({
                enforceStepRecordWithBLOBs: enforceStepList
            });
        }
    },

    //点击下载文件
    dowmloadFile: function (e) {
        let fileurl = e.currentTarget.dataset.url;
        let docName = e.currentTarget.dataset.name;
        let tempSuf = docName.split('.');
        let suffix = tempSuf[tempSuf.length - 1];
        let fileType = "doc,xls,ppt,pdf,docx,xlsx,pptx";
        let picSuffix = "bmp,jpg,png,tiff,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,jpeg";
        console.log("fileurl==", fileurl)
        wx.downloadFile({
            url: fileurl, //仅为示例，并非真实的资源
            success: function (res) {
                // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                console.log("读取文件成功=", res)
                // if (res.statusCode === 200) {
                var filePath = res.tempFilePath
                if (fileType.indexOf(suffix) != "-1") {
                    wx.openDocument({
                        filePath: filePath,
                        success: function (res) {
                            console.log('打开文档成功')
                        }
                    })
                } else if (picSuffix.indexOf(suffix.toLowerCase()) != "-1") {
                    wx.previewImage({
                        current: filePath, // 当前显示图片的http链接
                        urls: [filePath] // 需要预览的图片http链接列表
                    })
                }
            },
            fail: function (res) {
                console.log("读取文件失败=", res);
            }
        })
    },

    //步骤分支选择
    radioChange: function (e) {
      console.log('radio发生change事件，携带value值为：', e.detail.value);
      let nextStepId = e.detail.value.split('-')[0];
      let returnData = this.getSteptDataBySteptId(nextStepId, this);
      console.log("returnData====", returnData)
      if (returnData.isBranch == "Y") {
        let list = JSON.parse(returnData.branchJson);
        list.forEach(function (e) {
          e.text = e.nextStep.split("-")[1]
        });
        //弹框显示分支
        this.setData({
          branchItems: list,
        });
      } else {
        this.setData({
          branchNextSteptId: returnData.stepId
        });
        // this.subData(this.data.onChangeData)
      }
    },

    //根据steptId获取对应的stept值
    getSteptDataBySteptId: (steptId, _this) => {
      let list = _this.data.enforceStepList;
      let returndata = "";
      for (let i = 0; i < list.length; i++) {
        if (list[i].stepId == steptId) {
          returndata = list[i];
        }
      }
      return returndata;
    },

    //取消分支显示
    cancleBranch: function () {
      this.setData({
        showBranch: false
      });
    },

    //分支弹框确定
    confirmBranch: function () {
      console.log("this.data.onChangeData=", this.data.onChangeData)
      this.subData(this.data.onChangeData)
    },


    //点击完成提交相关数据
    subData: function (e) {
      let _this = this, sendData = {
        caseId: app.globalData.caseDetailData.caseId
      }, recordText = '', content = [], other = [];
      let { otherInput, enforceStepList, enforceStep, branchList } = this.data;
      if (this.data.stepDesc) {
        sendData.stepDesc = this.data.stepDesc;
        recordText = this.data.stepDesc + '。'
      } else {
        wx.showToast({ title: '描述不能为空', icon: 'none', duration: 800 });
        return;
      }
      if (enforceStep.isBranch === "N") {
        sendData.userVisual = e.detail.value.userVisual ? "Y" : "N";
      } else {
        sendData.userVisual = 'N'
      }
      if (sendData.userVisual == "Y") {
            sendData.delaySend = e.detail.value.delaySend ? "Y" : "N";
        }
      console.log(this.data.otherInput)
      for (let i = 0; i < otherInput.length; i++) {
        if (otherInput[i].value || (otherInput[i].value_date && otherInput[i].value_time)) {
          if (otherInput[i].type === 'dateTime') {
            if (otherInput[i].text == '开庭时间') {
              sendData.deadTime = otherInput[i].value_date + ' ' + otherInput[i].value_time + ":00";
            } else {
              other.push(otherInput[i].text + '：' + otherInput[i].value_date + ' ' + otherInput[i].value_time + ":00")
              content.push({
                text: otherInput[i].text,
                type: otherInput[i].type,
                value: otherInput[i].value_date + ' ' + otherInput[i].value_time + ":00"
              })
            }
          } else {
            other.push(otherInput[i].text + '：' + otherInput[i].value)
            content.push(otherInput[i])
          }
        } else {
          //wx.showToast({ title: otherInput[i].text + '不能为空', icon: 'none', duration: 800 });
          //return;
        }
      }
      if (other.length > 0) {
        sendData.recordText = recordText + ' ' + other.toString().replace(/,/g, '，')
      } else {
        sendData.recordText = recordText + ' '
      }
      sendData.content = JSON.stringify(content);
      if (!this.data.configType) {
        if (!e.detail.value.other_nextStep) {
          wx.showToast({ title: '请正确输入下一个步骤', icon: 'none', duration: 800 });
          return;
        }
        // if (!/^\d+$/.test(e.detail.value.other_periodDays)) {
        //   wx.showToast({ title: '请正确输入期限天数', icon: 'none', duration: 800 });
        //   return;
        // }
        // if (Number(e.detail.value.other_periodDays) > 5) {
        //   wx.showToast({ title: '期限天数不得大于5', icon: 'none', duration: 800 });
        //   return;
        // }
        sendData.stepName = e.detail.value.other_nextStep;
        sendData.periodDays = '5';
      } else {
        if (this.data.nextStepIndex !== 'none') {
          if (this.data.branchNextSteptId) {
            sendData.nextStepId = this.data.branchNextSteptId;
          } else {
            if (enforceStep.isBranch === "Y") {
              sendData.nextStepId = branchList[this.data.nextStepIndex].nextStep.split('-')[0];
            } else {
              sendData.nextStepId = enforceStepList[this.data.nextStepIndex].stepId;
            }
          }
        } else {
          if (enforceStep.nextStepId || enforceStep.isBranch === "Y" || !enforceStep.stepId) {
            wx.showToast({ title: '请选择下一步骤', icon: 'none', duration: 800 });
            return;
          }
        }
      }
      sendData.stepId = enforceStep.stepId;
      console.log(sendData);
      wx.showLoading({ title: ' ', mask: true })
      request.requestMisApi('post', "lawsuitStepRecords", sendData, (res) => {
        console.log(res);
        wx.hideLoading()
        if (res.code == '00') {
          // _this.get_enforceCurrInfos()
          // wx.showToast({ title: res.msg, icon: 'success' })
          wx.showToast({
            title: '成功',
            icon: 'success',
            duration: 2000
          })
          if (app.globalData.listRefresh.SY.tabtype == 'dynamics') {
            app.globalData.listRefresh.SY = {
              refresh: true,
            }
          }
          setTimeout(function () {
            wx.navigateBack({});
          }, 1500);
        } else {
          wx.showToast({ title: res.msg, icon: 'none' })
        }
      }, (res) => {
        wx.hideLoading()
        console.log("接口错误=", res)
      });
    },

    //完成当前步骤
    formSubmit: function (e) {
      this.setData({
        onChangeData: e,
        branchNextSteptId: ""
      });
      let { otherInput, enforceStepList, enforceStep, branchList } = this.data;

      //先判断有没有分支
      if (!this.data.configType) {
        this.subData(e)
      } else {
        if (this.data.nextStepIndex !== 'none') {
          if (!this.data.stepDesc) {
            wx.showToast({ title: '描述不能为空', icon: 'none', duration: 800 });
            return;
          }
          if (enforceStep.isBranch === "N") {
            let tempNextStepData = enforceStepList[this.data.nextStepIndex];
            if (tempNextStepData.isBranch == "Y") {
              // branchItems
              let branchList = JSON.parse(tempNextStepData.branchJson);
              branchList.forEach(function (e) {
                e.text = e.nextStep.split("-")[1]
              });
              //弹框显示分支
              this.setData({
                branchItems: branchList,
                showBranch: true
              });
            } else {
              this.subData(e)
            }
          } else {
            this.subData(e)
          }
        } else {
          if (enforceStep.nextStepId || enforceStep.isBranch === "Y" || !enforceStep.stepId) {
            wx.showToast({ title: '请选择下一步骤', icon: 'none', duration: 800 });
            return;
          }
        }
      }
    },
    formReset: function () {
        console.log('form发生了reset事件')
    },
    bindPickerChange: function (e) {
        // console.log('picker发送选择改变，携带值为', e)
        this.setData({
            nextStepIndex: e.detail.value
        })
    },
    bindbreakReasonsChange: function (e) {
        // console.log('picker发送选择改变，携带值为', e)
        this.setData({
            breakReasonsIndex: e.detail.value,
            breakReasonsDesc: this.data.breakReasons[e.detail.value].breakReasonName
        })
    },
    breakTypeChange: function (e) {
      console.log('picker发送选择改变，携带值为', e)
      this.setData({
        breakTypeIndex: e.detail.value
      })
    },
    bindbreakReasonsDescChange: function (e) {
        console.log('picker发送选择改变，携带值为', e)
        this.setData({
            breakReasonsDesc: e.detail.value
        })
    },
    stepDescChange: function (e) {
        console.log('picker发送选择改变，携带值为', e)
        this.setData({
            stepDesc: e.detail.value
        })
    },
    saveStepDesc: function () {
        let _this=this;
        wx.showLoading({ title: ' ', mask: true})
        request.requestMisApi('post', "lawsuitCurrInfos/saveStepDesc", {
            caseId: app.globalData.caseDetailData.caseId,
            stepDesc:this.data.stepDesc
        }, (res) => {
            console.log(res);
            wx.hideLoading()
            if (res.code == '00') {
                // _this.get_enforceCurrInfos()
                wx.showToast({ title: res.msg, icon: 'success' })
            } else {
                wx.showToast({ title: res.msg, icon: 'none' })
            }
        }, (res) => {
            wx.hideLoading()
            console.log("接口错误=", res)
        });
    },
    close:function(){
        this.setData({ modalClose: true })
    },
    close_finishs: function () {
        this.setData({ modalClose: false })
    },
    over: function () {
        let _this = this;
        wx.showLoading({ title: ' ', mask: true })
        request.requestMisApi('put', "lawsuitCurrInfos/backCases", { caseId: app.globalData.caseDetailData.caseId}, (res) => {
            console.log(res);
            wx.hideLoading()
            _this.setData({ modalClose: false })
            if (res.code == '00') {
                _this.get_enforceCurrInfos();
                _this.setData({ modalForInput: false });
                wx.showToast({ title: res.msg, icon: 'success' })
            } else {
                wx.showToast({ title: res.msg, icon: 'none' })
            }
        }, (res) => {
            wx.hideLoading()
            console.log("接口错误=", res)
        });
    },
    finishs: function () {
        let _this = this;
        wx.showLoading({ title: ' ', mask: true})
        request.requestMisApi('put', "lawsuitCurrInfos/finishs", { caseId: app.globalData.caseDetailData.caseId}, (res) => {
            console.log(res);
            wx.hideLoading()
            _this.setData({ modalClose: false })
            if (res.code == '00') {
                _this.get_enforceCurrInfos();
                _this.setData({ modalForInput: false });
                wx.showToast({ title: res.msg, icon: 'success' })
            } else {
                wx.showToast({ title: res.msg, icon: 'none' })
            }
        }, (res) => {
            wx.hideLoading()
            console.log("接口错误=", res)
        });
    },
    breakStep: function () {
      if (this.data.breakReasons.length>0){
        this.setData({ modalForInput: true })
      } 
    },
    canclebreakStep: function () {
        this.setData({ modalForInput: false })
    },
    confirmbreakStep: function () {
        // this.setData({ modalForInput: true })
        if (this.data.breakReasonsIndex === 'none') {
            wx.showToast({ title: '请选择中断原因', icon: 'none', duration: 800 });
            return;
        }
        if (!this.data.breakReasonsDesc) {
            wx.showToast({ title: '请输入描述', icon: 'none', duration: 800 });
            return;
        }
        let sendData = {
            caseId: app.globalData.caseDetailData.caseId,
            breakReasonId: this.data.breakReasons[this.data.breakReasonsIndex].breakReasonId,
            autoRenewDays: this.data.breakReasons[this.data.breakReasonsIndex].autoRenewDays,
            breakReasonName: this.data.breakReasons[this.data.breakReasonsIndex].breakReasonName,
        }
        let _this = this;
        if (this.data.ROLE_BreakForEver) {
          sendData.breakType = this.data.breakTypes[this.data.breakTypeIndex].id
        } else {
          sendData.breakType = '1';
        }
        console.log(sendData)
        wx.showLoading({ title: ' ', mask: true })
        request.requestMisApi('put', "lawsuitCurrInfos/breaks", sendData, (res) => {
            console.log(res);
            wx.hideLoading()
            if (res.code == '00') {
                _this.get_enforceCurrInfos();
                _this.setData({ modalForInput: false });
                wx.showToast({ title: res.msg, icon: 'success' })
            } else {
                wx.showToast({ title: res.msg, icon: 'none' })
            }
        }, (res) => {
            wx.hideLoading()
            console.log("接口错误=", res)
        });
    },
    otherInputChange: function (e) {
        console.log(e)
        let otherInput = this.data.otherInput;
        if (e.currentTarget.dataset.datetype === 'date') {
            otherInput[e.currentTarget.dataset.index].value_date = e.detail.value
        } else if (e.currentTarget.dataset.datetype === 'time') {
            otherInput[e.currentTarget.dataset.index].value_time = e.detail.value
        } else {
            otherInput[e.currentTarget.dataset.index].value = e.detail.value
        }
        this.setData({
            otherInput: otherInput
        })
    },
    changeCurrent: function (e) {
        console.log('changeCurrent====', e)
        if (e.detail.source == "touch") {
            // this.setData({
            //   currentNum: e.detail.current
            // })
            if (e.detail.current == '1') {
                this.tab2();
            } else if (e.detail.current == '2') {
                this.tab3();
            } else {
                this.tab1();
            }
        }
    },
    tab1: function () {
        setTimeout(()=>{
            this.setData({
                subZindex: 10
            })

        },100)
        this.setData({
            // subZindex:10,
            currentNum: 0
        })
    },
    tab2: function () {
        // console.log("详情==", JSON.stringify(this.data.enforceCurrInfos))
        //获取法官、财报、回款信息
        let table_faguan = this.data.enforceCurrInfos.lawsuitJudgeInfos;
        table_faguan.forEach(function(e){
            e.caseDate = e.caseDate.substring(0, 4) + "-" + e.caseDate.substring(4, 6) + "-" + e.caseDate.substring(6, 8)
        });
        let table_caibao = this.data.enforceCurrInfos.lawsuitPreservInfos;
        table_caibao.forEach(function (e) {
            e.preservStartDate = e.preservStartDate.substring(0, 4) + "-" + e.preservStartDate.substring(4, 6) + "-" + e.preservStartDate.substring(6, 8);
            e.preservEndDate = e.preservEndDate.substring(0, 4) + "-" + e.preservEndDate.substring(4, 6) + "-" + e.preservEndDate.substring(6, 8)
        });
        let table_huikuan = this.data.enforceCurrInfos.lawsuitAwardInfos;
        table_huikuan.forEach(function (e) {
            e.awardEndDate = e.awardEndDate.substring(0, 4) + "-" + e.awardEndDate.substring(4, 6) + "-" + e.awardEndDate.substring(6, 8)
        });
        this.setData({
            currentNum: 1,
            table_faguan: table_faguan,
            table_caibao: table_caibao,
            table_huikuan: table_huikuan
        })
    },
    tab3: function () {
        // console.log("案件进展列表=", JSON.stringify(this.data.enforceCurrInfos.enforceStepRecordWithBLOBs))
        let tempList = this.data.enforceCurrInfos.lawsuitStepRecordWithBLOBs;
        tempList.forEach(function (e) {
            let monthDate = util.timetrans(e.finishTime, "day");
            e.monthDate = monthDate.substring(5, 10)
            e.dayHM = util.timetrans(e.finishTime, "timeHM");
            e.openFile = false;
            if (e.lawsuitStepRecordDocs.length > 0) {
                let tempList = e.lawsuitStepRecordDocs;
                tempList.forEach(function (item) {
                    let tempUrl = item.docUrl.replace("https://winhc.oss-cn-shanghai.aliyuncs.com/", '');
                    item.docName = tempUrl.substring(10, tempUrl.length);
                });
                e.lawsuitStepRecordDocs = tempList;
            }
        });
        this.setData({
            currentNum: 2,
            enforceStepRecordWithBLOBs: tempList,
            tab3Flag: false
        })
    },

    //用户可见操作
    userCanseeChange: function (e) {
        console.log('picker发送选择改变，携带值为', e)
        this.setData({
            userCanseeType: e.detail.value
        })
        if (e.detail.value) {
            this.setData({
                userVisualResult :true
            })
        } else  {
            this.setData({
                userVisualResult: false
            })
        }
    },

    delaySendChange: function(e) {
        console.log('picker发送选择改变，携带值为', e)
        this.setData({
            delaySend: e.detail.value
        })
    },

    //添加法官
    addFaGuan: function(e){
        console.log('e=====',e)
        let det = e.currentTarget.dataset.det;
        let flag = e.currentTarget.dataset.flag;
        let dataInfo = {
            det: det,
            flag: flag,
            caseId: app.globalData.caseDetailData.caseId
        }
        wx.navigateTo({
            url: '../lstAddLawyer/lstAddLawyer?dataInfo=' + JSON.stringify(dataInfo),
        })
    },

    //点击删除法官
    delFaGuan: function(e){
        let _this = this;
        wx.showModal({
            title: '提示是否确认删除该记录?',
            content: '',
            success: function (res) {
                if (res.confirm) {
                    let id = e.currentTarget.dataset.id;
                    wx.showLoading({ title: '正在删除', mask: true })
                    request.requestMisApi("DELETE", "lawsuitJudgeInfos/" + id, {}, (res) => {
                        console.log(res);
                        wx.hideLoading()
                        if (res.code == '00') {
                            wx.showToast({ title: res.msg, icon: 'success' })
                            _this.initMethod();
                        } else {
                            wx.showToast({ title: res.msg, icon: 'none' })
                        }
                    }, (res) => {
                        wx.hideLoading()
                        console.log("接口错误=", res)
                    });
                } else if (res.cancel) {

                }
            }
        })

    },

    //添加财保
    addCaiBao: function(e){
        console.log('e=====', e)
        let det = e.currentTarget.dataset.det;
        let flag = e.currentTarget.dataset.flag;
        let dataInfo = {
            det: det,
            flag: flag,
            caseId: app.globalData.caseDetailData.caseId
        }
        wx.navigateTo({
            url: '../lstBaoQuan/lstBaoQuan?dataInfo=' + JSON.stringify(dataInfo),
        })
    },

    //点击删除财保、
    delCaiBao: function(e){
        let _this = this;
        wx.showModal({
            title: '提示是否确认删除该记录?',
            content: '',
            success: function (res) {
                if (res.confirm) {
                    let id = e.currentTarget.dataset.id;
                    wx.showLoading({ title: '正在删除', mask: true })
                    request.requestMisApi("DELETE", "awsuitPreservInfos/" + id, {}, (res) => {
                        console.log(res);
                        wx.hideLoading()
                        if (res.code == '00') {
                            wx.showToast({ title: res.msg, icon: 'success' })
                            _this.initMethod();
                        } else {
                            wx.showToast({ title: res.msg, icon: 'none' })
                        }
                    }, (res) => {
                        wx.hideLoading()
                        console.log("接口错误=", res)
                    });
                } else if (res.cancel) {

                }
            }
        })
    },

    //添加回款
    addHuiKuan: function(e){
        console.log('e=====', e)
        let det = e.currentTarget.dataset.det;
        let flag = e.currentTarget.dataset.flag;
        let _date = new Date();
        let Y = _date.getFullYear() + '-';
        var M = (_date.getMonth() + 1 < 10 ? '0' + (_date.getMonth() + 1) : _date.getMonth() + 1) + '-';
        var D = (_date.getDate() < 10 ? '0' + (_date.getDate()) : _date.getDate()) + ' ';
        let defaultDate = Y+M+D;
        if(flag == "edit"){
            defaultDate = det.awardEndDate;
        }
        this.setData({
            modalForHuiKuan:true,
            huiKuanFlag: flag,
            huiKuanFlagId: det.id,
            awardEndDate: defaultDate
        });
    },

    //点击删除回款
    delHuiKuan: function(e){
        let _this = this;
        wx.showModal({
            title: '提示是否确认删除该记录?',
            content: '',
            success: function (res) {
                if (res.confirm) {
                    let id = e.currentTarget.dataset.id;
                    wx.showLoading({ title: '正在删除', mask: true })
                    request.requestMisApi("DELETE", "lawsuitAwardInfos/" + id, {}, (res) => {
                        console.log(res);
                        wx.hideLoading()
                        if (res.code == '00') {
                            wx.showToast({ title: res.msg, icon: 'success' })
                            _this.initMethod();
                        } else {
                            wx.showToast({ title: res.msg, icon: 'none' })
                        }
                    }, (res) => {
                        wx.hideLoading()
                        console.log("接口错误=", res)
                    });
                } else if (res.cancel) {

                }
            }
        })
    },

    //回款到期日期触发
    startDateChange: function(e){
        this.setData({
            awardEndDate: e.detail.value
        });
    },

    //确认提交回款
    subHuiKuan: function(){
        let bodyInfo ={};
        bodyInfo.awardEndDate = this.data.awardEndDate.replace(/-/g, "");
        bodyInfo.caseId = app.globalData.caseDetailData.caseId;
        let method = "";
        if (this.data.huiKuanFlag == "add") {
            method = "POST";
        } else if (this.data.huiKuanFlag == 'edit') {
            method = "PUT";
            bodyInfo.id = this.data.huiKuanFlagId
        }
        console.log("bodyInfo===", bodyInfo)

        wx.showLoading({ title: ' ', mask: true})
        let _this = this;
        request.requestMisApi(method, "lawsuitAwardInfos", bodyInfo, (res) => {
            console.log(res);
            wx.hideLoading()
            if (res.code == '00') {
                wx.showToast({ title: res.msg, icon: 'success' })
                _this.setData({
                    modalForHuiKuan: false
                });
                _this.initMethod();
            } else {
                wx.showToast({ title: res.msg, icon: 'none' })
            }
        }, (res) => {
            wx.hideLoading()
            console.log("接口错误=", res)
        });
    },

    //取消回款
    cancleHuiKuan: function(){
        this.setData({
            modalForHuiKuan: false
        });
    },

    //编辑撤销步骤
    //点击编辑
    edit: function (e) {
        let edit_item = e.currentTarget.dataset.info;
        // console.log(edit_item)
        if ((new Date().getTime() - edit_item.finishTime * 1) < 30 * 60 * 1000) {
            this.setData({ showEdit: true, edit_value: edit_item.recordText, editId: edit_item.id })
        }else{
            this.setData({
                newDateTime: new Date().getTime()
            });
        }
    },

    //点击删除
    del: function (e) {
        let item = e.currentTarget.dataset.info;
        let _this = this;
        wx.showModal({
            title: '提示',
            content: '是否确认撤销该记录',
            confirmColor: '#1b82d1',
            success: function (res) {
                if (res.confirm) {
                    wx.showLoading({ title: '加载中', mask: true })
                    request.requestMisApi('delete', "lawsuitStepRecords/" + item.id, {}, (res) => {
                        console.log("成功=", res);
                        wx.hideLoading()
                        if (res.code == '00') {
                            _this.setData({ tab3Flag: true });
                            _this.get_enforceCurrInfos();
                            wx.showToast({
                                title: res.msg,
                                icon: 'success',
                                duration: 2000
                            })
                        } else {
                            wx.showToast({
                                title: res.msg,
                                icon: 'none',
                                duration: 2000
                            })
                        }
                    }, (res) => {
                        wx.hideLoading()
                        console.log("失败=", res)
                    });
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },

    //编辑保存
    edit_valueinput: function (e) {
        this.setData({
            edit_value: e.detail.value
        });
    },

    //编辑取消
    cancle: function (e) {
        this.setData({ showEdit: false })
    },
    //编辑确认
    confirm: function (e) {
        let edit_value = this.data.edit_value;
        if (!edit_value) {
            wx.showToast({
                title: '请输入描述',
                icon: 'none',
            })
            return;
        }
        let bodyInfo = {
            id: this.data.editId,
            recordText: edit_value
        };
        let _this = this;
        wx.showLoading({ title: '加载中', mask: true })
        request.requestMisApi('put', "lawsuitStepRecords", bodyInfo, (res) => {
            console.log("成功=", res);
            wx.hideLoading()
            if (res.code == '00') {
                _this.setData({ showEdit: false, tab3Flag: true });
                _this.get_enforceCurrInfos();
                wx.showToast({
                    title: res.msg,
                    icon: 'success',
                    duration: 2000
                })
            } else {
                wx.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 2000
                })
            }
        }, (res) => {
            wx.hideLoading()
            console.log("失败=", res)
        });
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        wx.stopPullDownRefresh()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

  //转发
  // onShareAppMessage: function (res) {
  //   if (res.from === 'button') {
  //     // 来自页面内转发按钮
  //     console.log("来自页面内的转发", res.target)
  //   }
  //   let This = this;
  //   console.log("app.globalData.caseDetailData.caseId=", app.globalData.caseDetailData.caseId)
  //   return {
  //     title: "转发测试",
  //     path: 'pages/lawsuitDetail/lawsuitDetail?caseId=' + app.globalData.caseDetailData.caseId,

  //     success: function (res) {
  //       // 转发成功
  //       console.log("转发成功返回数据=", res)
  //       wx.showShareMenu({
  //         // 要求小程序返回分享目标信息
  //         withShareTicket: true
  //       });

  //       if (res.shareTickets) {
  //         // 获取转发详细信息
  //         wx.getShareInfo({
  //           shareTicket: res.shareTickets[0],
  //           success(res) {

  //           },
  //           fail() { },
  //           complete() { }
  //         });
  //       }
  //     },
  //     fail: function (res) {
  //       // 转发失败
  //     },
  //     complete: function () {

  //     }
  //   }
  // },
})
